package enumandlambda;

import java.util.concurrent.TimeUnit;

/**
 * @author shkstart
 * 死锁实例
 * @create 2022-12-05-17:45
 */
public class Thread18 {
    public static void main(String[] args) {

        Object lockA = new Object();
        Object lockB= new Object();

        Thread t1 = new Thread(()->{
        //1.占有一把锁A
            synchronized (lockA) {
            System.out.println("线程1：获得锁A");
//            休眠1秒，让线程2有时间占有锁B
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //2.试图获取另一个线程的锁B
                synchronized (lockB){
                    System.out.println("线程1：获得锁B");
                }
            }
        });
        t1.start();

        Thread t2 = new Thread(()->{
            //1.占有一把锁B
            synchronized (lockB){
                System.out.println("线程2：获得锁B!!");
                //休眠1秒，让线程2能有充足的时间得到A
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //2.试图获取另一个线程的锁A
                synchronized (lockA){
                    System.out.println("线程2：获得锁A!!");
                }
            }


        });
        t2.start();

    }
}
